/*
 *
 * Copyright(c) TODO
 * licensing@realtor.org
 * http://www.realtor.org/license
 */

Ext.onReady(function()
{
	/**
	 * Gets the selected ml numbers from the search grid.
	 * @return string of mlnumbers, with an extra , generally ingnored
	 */
	var get_selected_ml_numbers = function()
	{
		var mls="";
		var grid = Ext.getCmp("results_grid");
        var sel = grid.getSelectionModel().getSelections();

		if(sel.length < AD.Globals.MAX_PROPS)
		{
			for(i=0; i<sel.length; i++)
			{
				mls += (sel[i].data.ml_number);
				mls += (",");
			}
		}
		return mls;
	};



	var fn_select_all = function(btn)
	{
		var grid = Ext.getCmp("results_grid");

		if ('Select All' == btn.getText())
		{
			AD.UI.grid_select_all();
			btn.setText('Deselect All');
		}
		else
		{
			grid.getSelectionModel().clearSelections();
			AD.UI.comps_clear();
			
			AD.UI.map_goog_clear();
			AD.UI.map_bing_clear();
			
			btn.setText('Select All');
		}
	};

	/**
	 * Pops up the appropriate report.
	 * @param Ext button with the id as the name of the report.
	 */
	var fn_report = function(btn)
	{
		var mls = get_selected_ml_numbers();

		if(3 < mls.length) //assumes atleast one mlnumber is selected???
		{
			var url = AD.Globals.URL_report + btn.id + "&ml_number=" + mls;
			window.open(url);
		}
		else
		{
			Ext.MessageBox.alert('Error', "Please select at least one property.");
		}
	};

	 var fn_reset_window_positions = function()
	    {
	    	 AD.UI.map_bing.setPosition(AD.Globals.client_width * 0.64, AD.Globals.client_height * 0.90);
	    	 AD.UI.map_goog_win.setPosition(AD.Globals.client_width * 0.33, AD.Globals.client_height * 0.90);
	    	 AD.UI.comps_panel.setPosition(AD.Globals.client_width * 0.02, AD.Globals.client_height * 0.90);
	    }

	var fn_clear_all = function()
	{
		AD.UI.ds_search_clear();

		AD.UI.grid_clear();
		
		AD.UI.map_goog_clear();
		AD.UI.map_bing_clear();
		
		AD.UI.comps_clear();
	};

	/**
	 * Reads the search form and refills the datastore with the matching resuls via xmlhtty.
	 * the mask is taken down on load of the datastore
	 */
	AD.UI.fn_search = function()
	{
		fn_clear_all();

		var frm = AD.UI.frm_search.getForm();
		var x = "";

		frm.items.each(function(item)
		{
			itn = item.getName();
			cmp = Ext.getCmp(itn);
			
			val = "";
			if(!cmp)
			{
				val = item.getRawValue();
			}else
			{
				val = cmp.getValue();	
			}
			
			if (('' != val) && ('Any' != val))
			{
				x += "&" + itn + "=" + val;
			}
		});

		var url = AD.Globals.URL_server + "search" + x;
		AD.Data.ds_search.proxy.conn.url = url;

		load_mask = new Ext.LoadMask(Ext.getBody(), {msg : 'Searching, please wait...'}, {removeMask : true}, {store : AD.Data.ds_search});

		AD.Data.ds_search.reload();
		load_mask.show();
	};
	 

	/**
	 * Dynamic drop downs to be used in the search form.
	 * Some of them are not dynamic, but they are precreated
	 * to make the form more readable.
	 */

	var city_store				= AD.Data.make_lookup_store('list_city');
	var exterior_store			= AD.Data.make_lookup_store('list_exterior');
	var school_district_store	= AD.Data.make_lookup_store('list_school_district');
	var status_store			= AD.Data.make_lookup_store('list_status');
	var style_store				= AD.Data.make_lookup_store('list_style');

	var metadata_store			= AD.Data.make_ajax_store(AD.Globals.URL_server + 'get_metadata_flds');

	var cb_city				= make_cb('City',				'city',					city_store,					'Any');
	var cb_exterior			= make_cb('Exterior',			'exterior',				exterior_store,				'Any');
	var cb_school_district	= make_cb('School District',	'school_district',		school_district_store,		'Any');
	var cb_status			= make_cb('Status',				'status',				status_store,				'Any');
	var cb_style			= make_cb('Style',				'style',				style_store,				'Any');

	var cb_md_lookup		= make_cb('Advanced',			'lookup',				metadata_store,				'');
	var cb_md_lookup_val	= make_cb('Search For',			'lookup_val',			metadata_store,				'');

	var cb_bathrooms		= make_cb('Bathrooms',			'bath_rooms',			AD.Data.num_store,			'');
	var cb_bedrooms			= make_cb('Bedrooms',			'bed_rooms',			AD.Data.num_store,			'');
	var cb_built_after		= make_cb('Year Built',			'year_built',			AD.Data.year_store,			'');
	var cb_garage			= make_cb('Garage',				'garage', 				AD.Data.num_store,			'');
	var cb_listing_date		= make_cb('Listing Date',		'listing_date',			AD.Data.date_store,			'');
	var cb_listing_price	= make_cb('Listing Price',		'listing_price',		AD.Data.dollar_store,		'');
	var cb_selling_date		= make_cb('Selling Date',		'selling_date',			AD.Data.date_store,			'Any');
	var cb_selling_price	= make_cb('Selling Price',		'selling_price',		AD.Data.dollar_store,		'');
	var cb_sqft				= make_cb('SQFT',				'sqft_above_ground',	AD.Data.sqft_store,			'');

	var tb_ml_number		= make_txt('MLS Number',		'ml_number',										'');
	var tb_street_name		= make_txt('Street Name',		'street_name',										'');
	var tb_zip				= make_txt('Zipcode',			'zip',												'');
	var tb_sub_division		= make_txt('Sub Division',		'sub_division',										'');

	AD.UI.enable_reports = function(bEnable)
	{
		enable_field("XML_MISMO",	bEnable);
		enable_field("XML_DETAIL",	bEnable);
		enable_field("PDF_LISTING",	bEnable);
		enable_field("PDF_DETAIL",	bEnable);
		enable_field("IMG_EXPORT",	bEnable);
	};

	function fn_reset()
	{
		AD.UI.frm_search.form.reset();
	}

	var lookup_queries = new Ext.form.TextArea(
	{
		id : 'saved_queries',
		name : 'saved_queries',
		fieldLabel : 'Built Query <br>or<br>Your own DMQL',
		width : AD.Globals.field_width,
		height : 127
	});
	
	var user_data_store;
	var fn_user_data_save_result = function()
	{
		load_mask.hide();
	}
	function fn_save()
	{
		var frm = AD.UI.frm_search.getForm();
		//form variables
		var frm_vars = "&frm_vars=[";
		frm.items.each(function(item)
		{
			itn = item.getName();
			cmp = Ext.getCmp(itn);
			val = (!cmp) ? item.getRawValue() : cmp.getValue();

			if (('' != val) && ('Any' != val))
			{
				frm_vars += "@" + itn + "=" + val;
			}
		});
		frm_vars += ']&';
		frm_vars = frm_vars.replace('[@', '[');	
		
		//Comps Selected
		var sel = AD.UI.get_sels_from_grid('results_grid');
		var len = sel.length;
		var comps ='';
		if ((!len) || (len == 0))
		{
			comps = '';
		}else
		{
			
			comps = "&comps=[";
			for (var i = 0; i < len; i++)
			{
				recid = sel[(len - i - 1)].id;
				rec = AD.Data.ds_search.getById(recid);

				if (!rec)
				{
					continue;
				}
				else
				{
					comps += rec.data.ml_number;
					comps += ','	
				}
			}
			comps += ']'
		}
		comps = comps.replace(',]', ']');
		
		var url = AD.Globals.URL_user_data + "save" + frm_vars + comps ;
		user_data_store	= AD.Data.make_ajax_store(url);
		user_data_store.on('load', function() {fn_user_data_save_result();});
		
		load_mask = new Ext.LoadMask(Ext.getBody(), {msg : 'Saving, please wait...'}, {removeMask : true}, {store : user_data_store});
		user_data_store.reload(); 
		load_mask.show();
	}
	function fn_file_open()
	{
		AD.UI.user_data_file_open();	
	}
	/**
	 * Search form panel with the form elements created above.
	 */
	AD.UI.frm_search  = new Ext.FormPanel(
	{
		title : 'Search',
		url : AD.Globals.URL_AD,
		width: AD.Globals.form_width,
		collapsible : true,
		autoScroll : true,
		bodyStyle : 'padding:5px 5px 0',
		buttonAlign : 'left',
		labelAlign : 'right',
		frame : true,
		id : 'frm_search',

		items:[
		       {
				   layout : 'column',
		    	   defaults : {layout : 'form', border : false, xtype : 'panel',bodyStyle : 'padding:0 5px 0 0'},
		    	   items : [
		    	            {items : [tb_street_name, cb_city, tb_zip, cb_school_district, tb_sub_division]},
		    	            {items : [tb_ml_number, cb_status, cb_listing_date, cb_listing_price, cb_selling_date, cb_selling_price]},
		    	            {items : [cb_bedrooms, cb_bathrooms, cb_sqft, cb_garage, cb_exterior, cb_style, cb_built_after]},
		    	            {items : [cb_md_lookup, cb_md_lookup_val, lookup_queries]}
					]
		       }],
		buttons : [
					{text : 'Search', 				handler : AD.UI.fn_search},
					{text : 'Select All',			handler : fn_select_all,id: 'SELECT_ALL',	disabled : true },
					{text : 'Reset Form',			handler : fn_reset	},
					{text : 'Reset Windows',		handler : fn_reset_window_positions	},

					{text : 'XML MISMO Report',		handler : fn_report, 	id: 'XML_MISMO',	disabled : true },
					{text : 'XML Detail Report',	handler : fn_report, 	id: 'XML_DETAIL',	disabled : true },
					{text : 'PDF Listing Report',	handler : fn_report,	id: 'PDF_LISTING',	disabled : true },
					{text : 'PDF Detail Report',	handler : fn_report, 	id: 'PDF_DETAIL',	disabled : true },
					{text : 'Export Images',		handler : fn_report, 	id: 'IMG_EXPORT',	disabled : true },

					{text : 'Save', 				handler : fn_save},
		       		{text : 'Open Saved', 			handler : fn_file_open},

					{text : 'Logout',				handler : fn_logout}
		]
	});

	AD.UI.frm_search.render('div_search');

	//var dataLoadMask = new Ext.LoadMask(Ext.getBody(), {msg : 'Loading, please wait...'});

	var stores_loaded = 0;

	function check_store(my_store, stores_loaded)
	{
		if (1 > my_store.totalLength)
		{
			if (++my_store.reload_count < 10)
			{
				my_store.reload();
			}
		}
		else
		{
			my_store.sort('value');
			stores_loaded++;
		}

		//if (6 == stores_loaded)
		//{
		//	dataLoadMask.hide();
		//}
		return stores_loaded;
	}

	function disable_flds()
	{
		disabled_store.each(function(r)
		{
			enable_field(r.data.key, false);
		});
		enable_field('lookup_val', false);
	}

	var disabled_store = AD.Data.make_ajax_store(AD.Globals.URL_server + 'get_disabled_flds');
	disabled_store.on('load', function() {disable_flds();});
	disabled_store.reload();

	city_store.reload_count = 0;
	city_store.on('load', function() {stores_loaded = check_store(city_store, stores_loaded);});
	city_store.reload();

	exterior_store.reload_count = 0;
	exterior_store.on('load', function() {stores_loaded = check_store(exterior_store, stores_loaded);});
	exterior_store.reload();

	school_district_store.reload_count = 0;
	school_district_store.on('load', function() {stores_loaded = check_store(school_district_store, stores_loaded);});
	school_district_store.reload();

	status_store.reload_count = 0;
	status_store.on('load', function() {stores_loaded = check_store(status_store, stores_loaded);});
	status_store.reload();

	style_store.reload_count = 0;
	style_store.on('load', function() {stores_loaded = check_store(style_store, stores_loaded);});
	style_store.reload();

	metadata_store.reload_count = 0;
	metadata_store.on('load', function() {stores_loaded = check_store(metadata_store, stores_loaded);});
	metadata_store.reload();

    cb_md_lookup.on('select', function()
    {
		var lookup_val_store = AD.Data.make_ajax_store(AD.Globals.URL_server + 'get_metadata_vals&field=' + cb_md_lookup.value);

		cb_md_lookup_val.bindStore(lookup_val_store);

		lookup_val_store.reload_count = 0;
		lookup_val_store.on('load', function() {stores_loaded = check_store(lookup_val_store, stores_loaded);});
		lookup_val_store.reload();

		enable_field('lookup_val', true);
    });

    cb_md_lookup_val.on('select', function()
    {
		var values = cb_md_lookup.value.split('@@');

		lookup_queries.setValue(values[1] + '=' + cb_md_lookup_val.value + ",\n" + lookup_queries.getValue());

		cb_md_lookup.clearValue();
		cb_md_lookup_val.clearValue();

		enable_field('lookup_val', false);
	});

    //This is used only to position the windows properly....If the user's windows gets lost,  s/he is expected to click on Reset Windows button 
    var firstTimer =  get_cookie('FIRST_TIMER');
    if('false' != firstTimer)
    {
        	fn_reset_window_positions();
    }

    set_cookie('FIRST_TIMER', 'false');
});
